<template>
  <van-floating-bubble
      axis="xy"
      icon="https://cqust-ted.oss-cn-chengdu.aliyuncs.com/4b6bd157-5c19-422f-b102-a309cf1b6e92.svg"
      magnetic="x"
      @click="onClickIntoUploder"
  />

  <div class="box">
    <div class="header-with-back">
      <div class="back-nav" @click="goToIndex">
        <van-icon name="arrow-left" />
        <span style="font-size: 1.2rem">资源共享</span>
      </div>
    </div>
    <!-- 中间内容 -->
    <div class="div-box">
      <div class="div-top">
        <van-search
            v-model="search"
            shape="round"
            placeholder="请输入搜索关键词"
            @search="onSearch"
        />
      </div>
    </div>
  </div>
  <div class="achievement-container">
<!--    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">-->
      <van-list
          :loading="loading"
          :finished="finished"
          finished-text="没有更多了"
          @load="onLoad"
          offset="300"
          :error.sync="error"
          error-text="暂无相关资源"
      >
        <van-row :gutter="[20, 6]" justify="start">
          <van-col
              span="11"
              v-for="item in list"
              :key="item.resourceId"
              @click="listButton(item)"
          >
            <div class="file-preview">
              <!-- 图片类型直接显示原图 -->
              <van-image
                  v-if="isImage(item.storagePath)"
                  width="100%"
                  height="160"
                  fit="cover"
                  radius="10px"
                  :src="item.storagePath"
              >
                <template v-slot:loading>
                  <van-loading type="spinner" size="20" />
                </template>
              </van-image>

              <!-- 非图片文件显示对应类型的图标 -->
              <van-image
                  v-else
                  width="100%"
                  height="160"
                  fit="contain"
                  radius="10px"
                  :src="getFileIcon(item.storagePath)"
              />

              <div class="ellipsis-text">{{ item.resourceDescription }}</div>
              <div class="ellipsis-text-username">{{ item.userName }}</div>
            </div>
          </van-col>
        </van-row>
      </van-list>
<!--    </van-pull-refresh>-->
  </div>
</template>

<script setup name="ResourceShareView" lang="ts">
import { ref, onMounted } from "vue";
import { showToast } from "vant";
import router from "../../Router";
import {searchByResourceNameUsingGet, updateAchievementArticleUsingPost3} from "../../Api/jiaoshimokuai";
import { useTeachingResourceStore } from '../../Store/modules/resource/TeachingResource.ts'

const useTeachingResource = useTeachingResourceStore();
// 搜索关键词
const search = ref("");
// 存储页面内容
const list = ref([]);
// 加载状态
const loading = ref(false);
// 是否加载完成
const finished = ref(false);
// 是否在刷新
const refreshing = ref(false);
// 是否出错
const error = ref(false);
// 当前页码
const currentPage = ref(1);
// 每页条数
const pageSize = ref(10000);
// 总条数
const total = ref(0);
// 全局加载状态
const isLoading = ref(true);

// 搜索功能
function onSearch() {
  list.value = [];
  currentPage.value = 1;
  finished.value = false;
  isLoading.value = true;
  getList();
}

// 返回到首页
function goToIndex() {
  router.push('/cqust/index');
}

// 跳转详情页
function listButton(resource) {
  useTeachingResource.fetchResourceDetail = resource;
  router.push({
    path: "/ReasourceShareXQView",
    query: { id: resource.resourceId }
  });
}

// 跳转资源上传页面
const onClickIntoUploder = () => {
  router.push("/ResourceShareUploaderView");
}


// 判断是否为图片
const isImage = (url) => {
  if (!url) return false;
  const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp'];
  return imageExtensions.some(ext => url.toLowerCase().endsWith(ext));
};

// 获取文件类型图标
const getFileIcon = (url) => {
  if (!url) return 'src/Assets/img/default.jpg';

  // 处理URL中的查询参数和哈希
  const cleanUrl = url.split('?')[0].split('#')[0];
  const extension = cleanUrl.split('.').pop().toLowerCase();

  const iconMap = {
    pdf: "https://cqust-ted.oss-cn-chengdu.aliyuncs.com/41bfab0a-823b-472e-9867-24ac7b3af901.jpg",
    doc: 'https://cqust-ted.oss-cn-chengdu.aliyuncs.com/d23895f5-c825-4b13-8c61-dd88f504054f.jpeg',
    docx: 'https://cqust-ted.oss-cn-chengdu.aliyuncs.com/ac21223d-ca2a-49ce-87a6-860fd823ad60.jpeg',
    ppt: 'https://cqust-ted.oss-cn-chengdu.aliyuncs.com/3a9c95ff-dd1d-4e8f-8e21-fdaa83da197b.jpg',
    pptx: 'https://cqust-ted.oss-cn-chengdu.aliyuncs.com/f02f030a-258e-4498-b0fa-c724224f2d53.jpg',
    xls: 'https://cqust-ted.oss-cn-chengdu.aliyuncs.com/362bb9eb-5f6e-4ead-bd2d-86c7998666fc.jpeg',
    xlsx: 'https://cqust-ted.oss-cn-chengdu.aliyuncs.com/362bb9eb-5f6e-4ead-bd2d-86c7998666fc.jpeg',
    mp4: 'https://cqust-ted.oss-cn-chengdu.aliyuncs.com/bd36d4e6-75ec-4747-ab65-74ca5bc302ae.jpeg',
    zip: 'https://cqust-ted.oss-cn-chengdu.aliyuncs.com/1c3b0823-c334-4358-89b5-ba2f3b7c9120.jpg',
    rar: 'https://cqust-ted.oss-cn-chengdu.aliyuncs.com/c1cab020-560c-47d2-8123-279bf7b5b41f.jpeg',
    default: 'https://cqust-ted.oss-cn-chengdu.aliyuncs.com/caf4d5aa-ae6f-49b3-a888-e93b80307e5c.jpg'
  };

  return iconMap[extension] || iconMap.default;
};


// 获取资源列表
async function getList() {
  try {
    if (refreshing.value) {
      currentPage.value = 1;
      list.value = [];
    }

    const resourceName = search.value.trim();
    let res;

    if (!resourceName) {
      // 查询全部资源（带分页参数）
      res = await updateAchievementArticleUsingPost3({
        pageNum: currentPage.value,
        pageSize: pageSize.value
      });
    } else {
      // 按名称搜索资源（带分页参数）
      res = await searchByResourceNameUsingGet({
        resourceName: resourceName,
        pageNum: currentPage.value,
        pageSize: pageSize.value
      });
    }

    if (res.data.code === 0) {
      const data = res.data.data;

      if (refreshing.value) {
        list.value = data;
        refreshing.value = false;
      } else {
        list.value = [...list.value, ...data];
      }

      // 更新总条数
      total.value = res.data?.total || res.total || data.length;

      // 判断是否加载完成
      if (data.length > 0) {
        if (data.length < pageSize.value) {
          finished.value = true;
        } else {
          currentPage.value++;
        }
      } else {
        showToast(res.message || "暂无相关资源");
        error.value = true;
      }
    }
  } catch (err) {
    showToast("加载失败，请稍后重试");
    error.value = true;
  } finally {
    loading.value = false;
    refreshing.value = false;
    isLoading.value = false;
  }
}


// 加载更多
function onLoad() {
  if (!finished.value) {

  }
}

// 下拉刷新
function onRefresh() {
  refreshing.value = true;
  finished.value = false;
  loading.value = true;
  // onLoad();
  // location.reload()
}

// 初始化加载
onMounted(() => {
  getList()
});
</script>

<style scoped>
/* 原有样式保持不变 */
* {
  padding: 0;
  margin: 0;
}

/*顶部盒子*/
.box {
  height: 7rem;
  min-width: 100%;
  position: fixed;
  z-index: 999;
  background-color: white;
}

.back-nav {
  position: fixed;
  left: 1%;
  top: 1.25%;
  display: flex;
  align-items: center;
  gap: 5px;
  cursor: pointer;
  color: rgb(83, 30, 88);
  padding: 0.5rem;
  z-index: 10;
  font-size: 0.9rem;
}

/*返回符号*/
.header-with-back .van-icon {
  position: static;
  font-size: 1.35rem;
}


/*大盒表单样式*/
.header-with-back {
  display: flex;
  flex-direction: column;
  margin-bottom: 2%;
  position: relative;
  background-color: white;
}

/*顶部盒子*/
.div-top {
  width: 100%;
  position: fixed;
}

.div-box {
  width: 100%;
  margin-top: 4rem;
}

/* 顶部搜索框 */
:deep(.van-search) {
  width: 97%;
  transition: width 0.5s ease, transform 0.5s ease;
  margin: auto;
}

/*循环大盒子*/
:deep(.van-row) {
  padding: 0.6rem 0 0 0 !important;
  background-color: white;
}

/* 每一个装内容的盒子 */
:deep(.van-col) {
  min-width: 48%;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);
  border-radius: 5%;
  background-color: white;
  padding: 0 !important;
  margin-left: 2%;
}

/*图片布局*/
:deep(.van-image) {
  min-height: 8rem;
}

/* 描述字体隐藏 */
.ellipsis-text {
  min-width: 95%;
  padding-left: 3%;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  min-height: 2rem;
  max-width: 97%;
  overflow: hidden;
  font-size: smaller;
  letter-spacing: 0.1rem;
}

/*用户名字体隐藏*/
.ellipsis-text-username {
  padding: 3% 1% 1% 3%;
  color: #999999;
  font-size: smaller;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 文件预览容器 */
.file-preview {
  height: 100%;
  display: flex;
  flex-direction: column;
}

/* 调整图片容器高度 */
:deep(.van-image) {
  height: 160px;
  background: white;
}


/* 加载动画样式 */
.loading-overlay {
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: rgba(255, 255, 255, 0.9);
  z-index: 1000;
}

.loading-wrapper {
  text-align: center;
}

.loading-wrapper .van-loading {
  margin-bottom: 10px;
}
.achievement-container {
  height: 100%; /* 根据需要设置固定高度 */
  overflow-y: auto; /* 允许垂直滚动 */
  padding: 10px; /* 内边距 */
  padding-top: 25%;
}

</style>
